package com.onenine.chat.view;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.FlexboxLayout;
import com.onenine.app.R;
import com.onenine.app.activity.RechargeActivity;
import com.onenine.app.adapter.ChatGiftAdapter;
import com.onenine.app.adapter.GameCategoryAdapter;
import com.onenine.app.db.DataManager;
import com.onenine.app.model.ChatGiftItem;
import com.onenine.app.model.GameCategory;
import com.onenine.app.request.SendGiftRequest;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.dialog.CommonTextDialog;

import java.util.List;

public class ChatOperationView extends FrameLayout implements View.OnClickListener {

    private FlexboxLayout mFbLayout;
    private RecyclerView mRvList;
    private View btnGame, btnGift, btnSendImage, btnGetCamera, btnVideoChat, btnAudioChat;
    private OnItemClickListener mOnItemClickListener;
    private String mTargetId;

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public ChatOperationView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChatOperationView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initLayout(context);
    }

    private void initLayout(Context context) {
        LayoutInflater.from(context).inflate(R.layout
                .layout_chatinput_expand, this, true);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mFbLayout = findViewById(R.id.fb_layout);
        mRvList = findViewById(R.id.rv_list_view);
        btnAudioChat = findViewById(R.id.tv_audio_chat);
        btnGame = findViewById(R.id.tv_game);
        btnGift = findViewById(R.id.tv_send_gift);
        btnSendImage = findViewById(R.id.tv_send_image);
        btnGetCamera = findViewById(R.id.tv_camera_image);
        btnVideoChat = findViewById(R.id.tv_video_chat);
        btnAudioChat.setOnClickListener(this);
        btnGame.setOnClickListener(this);
        btnGift.setOnClickListener(this);
        btnGame.setOnClickListener(this);
        btnSendImage.setOnClickListener(this);
        btnGetCamera.setOnClickListener(this);
        btnVideoChat.setOnClickListener(this);
    }

    /**
     * 加载礼物数据
     */
    private void loadGiftItems() {
        List<ChatGiftItem> chatGiftItemList = DataManager.getAllChatGifts();
        if (chatGiftItemList == null || chatGiftItemList.isEmpty()) {
            CDataProcessor.syncChatGifts(new Runnable() {
                @Override
                public void run() {
                    showChatGifts(DataManager.getAllChatGifts());
                }
            });
        } else {
            showChatGifts(chatGiftItemList);
        }
    }

    /**
     * 加载游戏种类数据
     */
    private void loadGameCategoryItems() {
        List<GameCategory> gameCategoryList = DataManager.getAllGameCategorys();
        if (gameCategoryList == null || gameCategoryList.isEmpty()) {
            CDataProcessor.syncGameCategory(new Runnable() {
                @Override
                public void run() {
                    showGameCategorys(DataManager.getAllGameCategorys());
                }
            });
        } else {
            showGameCategorys(gameCategoryList);
        }
    }

    /**
     * 显示礼物列表
     *
     * @param chatGiftItemList
     */
    private void showChatGifts(List<ChatGiftItem> chatGiftItemList) {
        mRvList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        ChatGiftAdapter adapter = new ChatGiftAdapter(chatGiftItemList);
        mRvList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ChatGiftItem giftItem = (ChatGiftItem) adapter.getItem(position);
                sendTargetGift(giftItem);
            }
        });
    }

    /**
     * 显示礼物列表
     *
     * @param gameCategoryList
     */
    private void showGameCategorys(List<GameCategory> gameCategoryList) {
        mRvList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        GameCategoryAdapter adapter = new GameCategoryAdapter(gameCategoryList);
        mRvList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //todo 进入游戏
                Toasty.showNormal("进入游戏");
            }
        });
    }

    /**
     * 发送礼物
     *
     * @param item
     */
    private void sendTargetGift(ChatGiftItem item) {
        if (mTargetId == null) {
            Toasty.showNormal("发送目标对象为空");
            return;
        }
        SendGiftRequest request = new SendGiftRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setMaintainPkId(item.getMaintainPkId());
        request.setTargetUserId(mTargetId);
        OkRequest.getInstance().withUrl(UrlConfig.SEND_GIFT)
                .withRequest(request).doRequest(ChatOperationView.class.getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                if (response.isSuccess()) {
                    Toasty.showNormal(R.string.gift_send_success);
                } else {
                    if (response.getMessage().contains("钻石不足")) {
                        //fixme 以后要有余额不足的状态来判断
                        new CommonTextDialog.Builder(ChatOperationView.this.getContext())
                                .setText(response.getMessage()).setOkText(R.string.recharge)
                                .setOnOkClickListener(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        RechargeActivity.launchActivity(ChatOperationView.this.getContext());
                                    }
                                }).builder().show();
                    } else {
                        Toasty.showNormal(response.getMessage());
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_send_gift) {
            mFbLayout.setVisibility(View.GONE);
            mRvList.setVisibility(View.VISIBLE);
            loadGiftItems();
            return;
        } else if (v.getId() == R.id.tv_game) {
            mFbLayout.setVisibility(View.GONE);
            mRvList.setVisibility(View.VISIBLE);
            loadGameCategoryItems();
        }
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(v, Integer.parseInt(v.getTag().toString()));
        }
    }

    /**
     * 显示礼物面板
     */
    public void showGiftBoard() {
        btnGift.callOnClick();
    }

    /**
     * 设置列表项事件
     *
     * @param mOnItemClickListener
     */
    public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }

    /**
     * 设置单聊或群聊
     *
     * @param type
     */
    public void setPrivateOrGroupExpandContent(int type, String targetId) {
        mTargetId = targetId;
        if (type > 0) {
            btnGame.setVisibility(View.GONE);
            btnGift.setVisibility(View.GONE);
            btnVideoChat.setVisibility(View.GONE);
            btnAudioChat.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 恢复菜单操作view
     */
    public void resetOriginView() {
        mFbLayout.setVisibility(View.VISIBLE);
        mRvList.setVisibility(View.GONE);
    }

}
